// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm.analysis;

import org.objectweb.asm.tree.analysis.Value;

import com.dustedpixels.common.Objects;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class FlowValue implements Value {
  static FlowValue newLike(Value value) {
    if (value == null) {
      return null;
    } else {
      return new FlowValue(value.getSize(), null, null);
    }
  }
  
  static FlowValue merged(FlowValue value1, FlowValue value2) {
    return new FlowValue(value1.getSize(), value1, value2);
  }

  private final int size;
  private final FlowValue value1;
  private final FlowValue value2;
  
  private FlowValue(int size, FlowValue value1, FlowValue value2) {
    this.size = size;
    this.value1 = value1;
    this.value2 = value2;
  }
  
  public int getSize() {
    return size;
  }

  public boolean covers(Value value) {
    return (value == this) ||
           (value1 != null && value1.covers(value)) ||
           (value2 != null && value2.covers(value));
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if (!(obj instanceof FlowValue)) return false;
    FlowValue otherValue = (FlowValue) obj;
    return (size == otherValue.size) &&
           Objects.eq(value1, otherValue.value1) &&
           Objects.eq(value2, otherValue.value2);
  }

  @Override
  public String toString() {
    return "FlowValue(" + size + "," + value1 + "," + value2 + ")";
  }
}
